package com.stu.design_patterns.proxy._02_dynamic_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

// 测试 JDK 动态代理
public class Client1 {
  public static void main(String[] args) {
    Marry marry = new Newcomer();
    MarryHandler handler = new MarryHandler(marry);
    Marry marryProxy = (Marry)Proxy.newProxyInstance(ClassLoader.getSystemClassLoader(), marry.getClass().getInterfaces(), handler);
    // Marry marryProxy = (Marry)Proxy.newProxyInstance(marry.getClass().getClassLoader(), marry.getClass().getInterfaces(), handler);
    marryProxy.happyMarry();
    marryProxy.test();
  }
}

 // 抽象角色
interface Marry {
  // 真实业务——结婚
  void happyMarry();
  void test();
}

// 真实角色
class Newcomer implements Marry {
  @Override
  public void happyMarry() { System.out.println("一对新人结为夫妻"); }
  @Override
  public void test() {
    System.out.println("test");
  }
}

// 真实角色
class Dog implements Marry {
  private String name;
  public Dog(String name) { this.name = name; }
  @Override
  public void happyMarry() {
    System.out.println("狗高兴地结婚了："+name);
  }
  @Override
  public void test() {
    System.out.println("狗测试");
  }
}

// 调用处理器
class MarryHandler implements InvocationHandler {
  // 真实角色实例
  private Object target;
  public MarryHandler(Object target) { this.target = target; }

  // 代理角色最终调用的都是此方法
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    before();// 前置任务
    Object returnValue = method.invoke(target, args);
    after();// 后置任务
    return returnValue;
  }

  public void before() { System.out.println("布置酒席"); }
  public void after() { System.out.println("打扫卫生"); }
}